import moment from 'moment'
import config from '@/config'
import fs from 'fs'
import { dirExist,checkCode, getJWTPayload } from '@/common/utils'
import uuid from 'uuid/dist/v4'
import User from '@/model/User'
import Post from '@/model/Post'
import UserCollect from '@/model/UserCollect'
import Links from '@/model/Link'
import qs from 'qs'
class ContentController {
  constructor() { }
  async uploadImg (ctx) {
    const file = ctx.request.files.file
    const ext = file.name.split('.').pop()
    const dir = `${config.uploadPath}/${moment().format('YYYYMMDD')}`
    // 判断路径是否存在，不存在则创建
    const rs = await dirExist(dir)

    const picname = uuid()
    const destPath = `${dir}/${picname}.${ext}`
    const reader = fs.createReadStream(file.path)
    const upStream = fs.createWriteStream(destPath)

    const filePath = `/${moment().format('YYYYMMDD')}/${picname}.${ext}`

    // method 1
    reader.pipe(upStream)

    const stat = fs.statSync(file.path)
    // method 2
    // let totalLength = 0
    // reader.on('data', function (chunk) {
    //   totalLength += chunk.length
    //   if (upStream.write(chunk) === false) {
    //     reader.pause()
    //   }
    // })

    // reader.on('drain', function () {
    //   reader.resume()
    // })

    // reader.on('end', function () {
    //   upStream.end()
    // })
    ctx.body = {
      code: 200,
      msg: '图片上传成功',
      data: filePath
    }
  }

  // 添加新帖
  async addPost (ctx) {
    const { body } = ctx.request
    let sid = body.sid, code = body.code
    let ckCode = await checkCode(sid, code);
    if (ckCode) {
      const obj = await getJWTPayload(ctx.header.authorization)
      // 判断用户的解纷是否>fav ,否则积分不够不能发帖
      const user = await User.findByID({_id:obj.id})
      // 用户积分足够的时候，新建post,减掉用户的积分
      if (user.favs < body.fav) {
        ctx.body = {
          code: 501,
          msg:'积分不足'
        }
      } else {
        await User.updateOne({ _id: obj.id }, {  $inc: { favs: -body.fav }})
      }
      const newPost = new Post(body)
      newPost.uid = obj.id
      const result = await newPost.save()
      ctx.body = {
        code:200,
        msg: '成功的保存文章',
        data:result
      }
    }else{
      ctx.body = {
        code:500,
        msg: '图片验证码验证失败',
      }
    }
    
  }

  // 获取帖子列表
  async getPostList (ctx) {
    const body = qs.parse(ctx.query)
    const sort = body.sort ? body.sort : 'created'
    const page = body.page ? parseInt(body.page) : 0
    const limit = body.limit ? parseInt(body.limit) : 20
    const options = {}
    if (body.title) {
      options.title = { $regex: body.title }
    }
    if (body.catalog && body.catalog.length > 0) {
      options.catalog = { $in: body.catalog }
    }
    if (body.isTop) {
      options.isTop = body.isTop
    }
    if (body.isEnd) {
      options.isEnd = body.isEnd
    }
    if (body.status) {
      options.status = body.status
    }
    if (typeof body.tag !== 'undefined' && body.tag !== '') {
      options.tags = { $elemMatch: { name: body.tag } }
    }
    const result = await Post.getList(options, sort, page, limit)
    const total = await Post.countList(options)

    ctx.body = {
      code: 200,
      data: result,
      msg: '获取文章列表成功',
      total: total
    }
    
  }

  // 温馨提醒
  async getTips (ctx) {
    const result = await Links.find({ type: 'tips' })
    ctx.body = {
      code: 200,
      data: result,
    }
    
  }

  // top
  async getTop (ctx) {
    const result = await Links.find({ type: 'top' })
    ctx.body = {
      code: 200,
      data: result,
    }
    
  }

  // 友情链接
  async getLinks (ctx) {
    const result = await Links.find({ type: 'link' })
    ctx.body = {
      code: 200,
      data: result,
    }
  }

  // 获取文章详情
  async getPostDetail (ctx) {
    const params = ctx.query
    if (!params.tid) {
      ctx.body = {
        code: 500,
        msg: '文章id为空'
      }
      return false
    }
    const post = await Post.findByTid(params.tid)
    if (!post) {
      ctx.body = {
       code: 500,
        msg: '获取文章详情失败'
      }
      return
    }
    let isFav = 0
    // 判断用户是否传递Authorization的数据，即是否登录
    if (
      typeof ctx.header.authorization !== 'undefined' &&
      ctx.header.authorization !== ''
    ) {
      const obj = await getJWTPayload(ctx.header.authorization)
      const userCollect = await UserCollect.findOne({
        uid: obj._id,
        tid: params.tid
      })
      if (userCollect && userCollect.tid) {
        isFav = 1
      }
    }
    const newPost = post.toJSON()
    newPost.isFav = isFav
    // 更新文章阅读记数
    const result = await Post.updateOne(
      { _id: params.tid },
      { $inc: { reads: 1 } }
    )
    if (post._id && result.ok === 1) {
      ctx.body = {
        code: 200,
        data: newPost,
        msg: '查询文章详情成功'
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '获取文章详情失败'
      }
    }
  }



}
export default new ContentController()
